<?php
/**
* php定时执行工具，返回执行时间图
*/
class GiftStatisticsClass {

    private $interval = 0;
    private $lastUpTime = 0;
    private $isDelay = false;
    private $delayInterval = 0;
    private $nowtime = 0;
    private $timeMap = array();

    /**
    *@param integer $interval 间隔时间
    *@param integer $lasttime 最后更新时间
    *@param integer $nowtime 当前时间
    */
    public function main($interval = 5, $lasttime = 0, $nowtime = 0) {
        $this->interval = $interval * 60;
        $this->nowtime = empty($nowtime) == true ? time() : $nowtime;
        $this->lastUpTime = $lasttime;
        if ($this->lastUpTime + $this->interval > $this->nowtime) {
            return $this;
        }
#延迟是否一天的时间
        $this->delayInterval = $this->daysbetweendates($this->lastUpTime, $this->nowtime);

        if ($this->delayInterval > 0) {
            $this->isDelay = true;
        }

        $this->distributeTimeMap();
        return $this;
    }

    /**
     * 时间图打印预览测试
     */
    public function dump() {
        $i = 0;
        foreach ($this->timeMap as $item) {
            $i++;
            echo '<div style="border:#333 1px solid;margin:10px 0;padding:20px;"><p>' . $i . '</p><p>Starttime:' . date('Y-m-d H:i:s', $item['s']) . '</p><p>Endtime:' . date('Y-m-d H:i:s', $item['e']) . '</p></div>';
        }
        return $this;
    }

    /**
    *注销
    */
    public function destroy() {
        $this->interval = $this->lastUpTime = $this->delayInterval = $this->nowtime = 0;
        $this->isDelay = false;
        $this->timeMap = array();
        return $this;
    }
    
    public function getNowtime(){
        return $this->nowtime;
    }
    
    public function getTimeMap(){
        return $this->timeMap;
    }
    


    /**
     * 分图时间图
     */
    private function distributeTimeMap() {

        if ($this->delayInterval == 0) {
            $this->timeMap[] = array(
                's' => $this->lastUpTime,
                'e' => $this->nowtime
                );
        } else {

            for ($i = 0; $i <= $this->delayInterval; $i++) {
                $startTime = $i == 0 ? $this->lastUpTime : strtotime(date('Y-m-d 0:0:0', strtotime('+' . $i . ' day', $this->lastUpTime)));
                $endTime = $i == 0 ? strtotime(date('Y-m-d 23:59:59', $this->lastUpTime)) : strtotime(date('Y-m-d 23:59:59', strtotime('+' . $i . ' day', $this->lastUpTime)));
                $this->timeMap[] = array(
                    's' => $startTime,
                    'e' => $endTime
                    );
            }
        }
    }

    /**
     * 计算两个时间差的天数
     * @param type $date1
     * @param type $date2
     * @return type
     */
    private function daysbetweendates($date1, $date2) {
        $date1 = strtotime(date('Y-m-d 23:59:59', $date1));
        $date2 = strtotime(date('Y-m-d 23:59:59', $date2));
        $days = ceil(($date2 - $date1) / 86400);
        return $days;
    }

}
